package org.csu.mypetstore.web.servlets;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.util.Result;
import org.csu.mypetstore.util.ResultForUpdateCart;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

public class CartAutoRefreshServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] str1 = req.getParameterValues("ids");
        System.out.println(str1[0]);

        String []id = str1[0].split(",");

        String[] str2 = req.getParameterValues("amounts");
        System.out.println(str2[0]);

        String[] amount = str2[0].split(",");

        int length = amount.length;


        Cart cart;
        HttpSession session = req.getSession();
        cart = (Cart)session.getAttribute("cart");

        Iterator<CartItem> cartItemIterator = cart.getAllCartItems();

        for (int i=0;i<length;i++) {

            CartItem cartItem = (CartItem) cartItemIterator.next();

            try {
                cart.setQuantityByItemId(id[i], Integer.parseInt(amount[i]));
                if (Integer.parseInt(amount[i]) < 1) {
                    cartItemIterator.remove();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        session.setAttribute("cart", cart);


        Cart cart2 = (Cart)session.getAttribute("cart");
        Iterator<CartItem> cartItemIterator2 = cart2.getAllCartItems();
        String quantityAll = "";
        while (cartItemIterator2.hasNext()) {
            //产品数量增加
            CartItem cartItem2 = cartItemIterator2.next();
            int quantity2 = cartItem2.getQuantity();
            quantityAll += quantity2 + "," + cartItem2.getTotal() + ",";

        }
        quantityAll = quantityAll +cart2.getSubTotal();
        System.out.println(quantityAll);

        resp.setContentType("text/xml");
        PrintWriter out = resp.getWriter();
        out.write(quantityAll);

        out.flush();
        out.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
